package com.example.myblog_ssm.controller;

import com.example.myblog_ssm.common.AjaxResult;
import com.example.myblog_ssm.common.AppVariable;
import com.example.myblog_ssm.common.PasswordUtils;
import com.example.myblog_ssm.common.UserSessionUtils;
import com.example.myblog_ssm.entity.UserInfo;
import com.example.myblog_ssm.entity.VO.UserInfoVO;
import com.example.myblog_ssm.service.ArticleService;
import com.example.myblog_ssm.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-03-20
 * Time: 22:42
 */
@RestController //返回的非静态页面
@RequestMapping("/user")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;
    @Resource
    private ArticleService articleService;

    /**
     * 注册新用户
     *
     * @param userInfo Spring MVC ⾃动实现参数对象的赋值
     * @return 统一返回格式AjaxResult
     */
    @RequestMapping("/reg")
    public AjaxResult reg(UserInfo userInfo) {
        //非空校验 -  验证前端参数
        if (userInfo.getUsername() != null && StringUtils.hasLength(userInfo.getUsername()) && StringUtils.hasLength(userInfo.getPassword())) {
            userInfo.setPassword(PasswordUtils.encrypt(userInfo.getPassword()));
            return AjaxResult.success(userInfoService.insert(userInfo));
        } else {
            return AjaxResult.fail(-1, "非法参数");
        }
    }

    /**
     * 登录验证
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public AjaxResult log(HttpServletRequest request, String username, String password) {
        //1、非空校验
        if (!StringUtils.hasLength(username) && !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "非法请求");
        }
        UserInfo userInfo = userInfoService.getUserByName(username);
        //用户名有效
        if (userInfo != null && userInfo.getId() > 0) {
            //两个密码是否相同
            if (PasswordUtils.check(password, userInfo.getPassword())) {
                //登录成功
                //将用户存储到session
                HttpSession session = request.getSession(true);

                session.setAttribute(AppVariable.USER_SESSION_KEY, userInfo);
                userInfo.setPassword(""); //返回前端之前隐藏敏感信息

                return AjaxResult.success(userInfo);
            }
        }
        //用户名无效或密码不正确
        return AjaxResult.success(0, null);
    }


    /**
     * 获取登录用户左侧用户个人信息 [username + artcount]
     *
     * @param request
     * @return
     */
    @RequestMapping("/showinfo")
    public AjaxResult showInfo(HttpServletRequest request) {
        UserInfoVO userInfoVO = new UserInfoVO();
        //1.得到当前登录用户  | 登录用户相关操作这个功能模块需要多次调用,写成一个通用的方法
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null) {
            return AjaxResult.fail(-1, "非法请求");
        }
        //通过spring框架提供的方法来进行深拷贝
        BeanUtils.copyProperties(userInfo, userInfoVO);
        //2.得到用户发表的文章总数
        UserInfoVO userInfoVO1 = articleService.getArtCountByUid(userInfo.getId());

        userInfoVO.setArtCount(userInfoVO1.getArtCount());
        userInfoVO.setTotalrcount(userInfoVO1.getTotalrcount());
        return AjaxResult.success(userInfoVO);
    }

    /**
     * 退出登录功能
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public AjaxResult del(HttpSession session) {
        //删除sessionId
        session.removeAttribute(AppVariable.USER_SESSION_KEY);
        return AjaxResult.success(1);
    }

    /**
     * 文章详情页左侧作者信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/getuserbyid")
    public AjaxResult getUserById(Integer id) {
        //1.非空校验
        if (id == null || id < 0) {
            System.out.println(id);
            return AjaxResult.fail(-1, "非法参数");
        }
        UserInfo userInfo = userInfoService.getUserById(id);
        if (userInfo == null) {
            return AjaxResult.fail(-2, "非法参数");
        }
        UserInfoVO userInfoVO = new UserInfoVO();
        //深拷贝
        BeanUtils.copyProperties(userInfo, userInfoVO);
        UserInfoVO userInfoVO1 = articleService.getArtCountByUid(id);
        userInfoVO.setArtCount(userInfoVO1.getArtCount());
        userInfoVO.setTotalrcount(userInfoVO1.getTotalrcount());
        userInfoVO.setPassword("");
        return AjaxResult.success(userInfoVO);
    }

    /**
     * 修改/忘记密码
     *
     * @param username
     * @param phonenumber
     * @param password
     * @return
     */
    @RequestMapping("/findpsw")
    public AjaxResult findpsw(String username, String phonenumber, String password) {
        //非空校验
        if (!StringUtils.hasLength(username) && !StringUtils.hasLength(password) || !StringUtils.hasLength(phonenumber)) {
            return AjaxResult.fail(-1, "非法请求");
        }
        //根据用户名查找用户 用户名是否输入正确
        UserInfo seekuser = userInfoService.getUserByName(username);
        if (seekuser == null) {
            return AjaxResult.fail(-2, "用户名输入错误!");
        }
        //尝试通过手机号查找用户信息修改密码
        //手机号不匹配
        if (!seekuser.getPhonenumber().equals(phonenumber)) {
            return AjaxResult.fail(-3, "手机号验证失败,请重试!");
        }
        //手机号匹配
        //a.先对用户传入的密码加盐
        String slatpassword = PasswordUtils.encrypt(password);
        seekuser.setPassword(slatpassword);
        //修改密码
        return AjaxResult.success(userInfoService.findpsw(seekuser));
    }

    @RequestMapping("/changepsw")
    public AjaxResult changepsw(HttpServletRequest request, String phonenumber, String password) {
        //非空校验
        if (!StringUtils.hasLength(password) || !StringUtils.hasLength(phonenumber)) {
            return AjaxResult.fail(-1, "非法请求");
        }
        //根据登录的session获取用户信息
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null || userInfo.getId() < 0) {
            return AjaxResult.fail(-2, "用户信息有误");
        }
        //修改密码
        //尝试通过手机号查找用户信息修改密码
        //手机号不匹配
        if (!userInfo.getPhonenumber().equals(phonenumber)) {
            return AjaxResult.fail(-3, "手机号验证失败,请重试!");
        }
        //手机号匹配
        //a.先对用户传入的密码加盐
        String slatpassword = PasswordUtils.encrypt(password);
        userInfo.setPassword(slatpassword);
        //修改密码
        return AjaxResult.success(userInfoService.findpsw(userInfo));
    }

    @RequestMapping("/nickname")
    public AjaxResult updatenickname(HttpServletRequest request, String nickname) {
        if (!StringUtils.hasLength(nickname)) {
            return AjaxResult.fail(-1, "非法参数");
        }
        //根据登录的session获取用户信息
        UserInfo userInfo = UserSessionUtils.getUserBySession(request);
        if (userInfo == null || userInfo.getId() < 0) {
            return AjaxResult.fail(-2, "用户信息有误");
        }
        userInfo.setNickname(nickname);
        HttpSession session = request.getSession(false);
        UserInfo userInfo1 = (UserInfo) session.getAttribute(AppVariable.USER_SESSION_KEY);
        userInfo1.setNickname(nickname);
        session.setAttribute(AppVariable.USER_SESSION_KEY, userInfo1);
        //更新昵称
        return AjaxResult.success(userInfoService.updatenickname(userInfo));

    }
}
